/*
 * ClientThread.java
 *
 * Created on August 13, 2006, 4:58 PM
 *
 */
package org.letva.copie.subserver.threads;

import java.io.*;
import java.net.*;
import org.letva.copie.common.exceptions.EndClientThreadException;
import org.letva.copie.subserver.*;

/**
 *
 * @author Vuk Nikolic
 */
public class ClientThread extends Thread {

	/** Creates a new instance of ClientThread */
	public ClientThread(Socket s, SubServer ss) {
		mySocket = s;
		mySubServer = ss;
		mySubServer.writeLog("ClientThread: created.");
	}

	@Override
	public void run() {
		System.out.println("ClientThread: poceo run");
		// cim smo dosli do ovde, znaci neki klijent na drugom racunaru je uradio
		// paste from ovog podservera, sto znaci da njemu treba da prosledim
		// moj Clipboard, odosno Clipboard mojih Clienata, ali posto sam na
		// ISTOJ MASINI to je moj sistemski klipbord.
		try {
			ObjectOutput out = new ObjectOutputStream(mySocket.getOutputStream());
			ObjectInput in = new ObjectInputStream(mySocket.getInputStream());

			Object inputMessage = null;
			Object outputMessage = null;
			// od clienta dobijamo poruku ili kao zahtev da vidimo koji sve
			// podserveri postoje ili da od tog odredjenog podservera dobijemo
			// njegov klipbord.
			while (!theEnd) {
				inputMessage = in.readObject();
				// Message koji kaze Protocolu sta da radi
				outputMessage = myProtocol.messageFromClient(inputMessage);
				out.writeObject(outputMessage);
				out.flush();
			}

			in.close();
			out.close();
			mySocket.close();
			// POSTO SMO ODRADILI SLANJE PASTE FROM-A A NIJE DOSLO
			// DO EXCEPTIONA POVECAVAM BROJ MREZNIH PREBACIVANJA

			// ako dodje do exceptiona subserver ne prikazuje nista,
			// samo smanjuje broj konektovanih, dok na clientskoj strani
			// ispisujem svaki vid exceptiona
		} catch (SocketException ex) {
		} catch (SocketTimeoutException ex) {
		} catch (ClassNotFoundException ex) {
		} catch (IOException ex) {
		} catch (EndClientThreadException ex) {
			try {
				mySocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		mySubServer.decActiveClientThreads();
		System.out.println("ClientThread: gotov run");
	}
	private SubServerProtocol myProtocol = SubServer.getProtocol();
	private boolean theEnd = false;
	private Socket mySocket = null;
	private SubServer mySubServer = null;
}
